package com.das.mechanic_base.mvp.view.finish;

import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.Postcard;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.das.mechanic_base.R;
import com.das.mechanic_base.R2;
import com.das.mechanic_base.app.X3AppRouterConstants;
import com.das.mechanic_base.app.X3Constent;
import com.das.mechanic_base.app.X3RouterCenter;
import com.das.mechanic_base.base.X3BaseActivity;
import com.das.mechanic_base.bean.alone.CloseWebviewAcivityBean;
import com.das.mechanic_base.def.finish.X3WorkType;
import com.das.mechanic_base.mvp.contract.finish.AloneFinishContract;
import com.das.mechanic_base.mvp.presenter.finish.X3AloneFinishPresenter;
import com.das.mechanic_base.utils.SpHelper;
import com.das.mechanic_base.utils.X3StatusBarUtil;
import com.hjq.toast.ToastUtils;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;

import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * Created by chensi on 2018/3/13.
 */
@Route(path = X3AppRouterConstants.Router.WORK_FINISH)
public class X3WorkFinishActivity extends X3BaseActivity<X3AloneFinishPresenter> implements AloneFinishContract.View {

    @BindView(R2.id.tv_status)
    TextView tv_status;
    @BindView(R2.id.tv_content)
    TextView tv_content;
    @BindView(R2.id.ll_work)
    LinearLayout ll_work;
    @BindView(R2.id.ll_alone)
    LinearLayout ll_alone;
    @BindView(R2.id.tv_start_ih)
    TextView tv_start_ih;
    @BindView(R2.id.tv_refresh)
    TextView tv_refresh;
    @BindView(R2.id.tv_send)
    TextView tv_send;
    @BindView(R2.id.tv_work)
    TextView tv_work;
    @BindView(R2.id.iv_show)
    ImageView iv_show;
    @BindView(R2.id.tv_check)
    TextView tv_check;
    @BindView(R2.id.tv_back)
    TextView tv_back;
    @BindView(R2.id.tv_plan)
    TextView tv_plan;
    @BindView(R2.id.ll_first)
    LinearLayout ll_first;

    private String carNum;
    private long carId,workBaseId,reportStatus,receiveBaseId;
    private int type;
    private Observable<Long> delay;

    private boolean isOpenSdk;

    private boolean isLoad;

    @Override
    protected int getLayoutId() {
        return R.layout.x3_work_finish_fragment;
    }

    @Override
    protected void initView() {
        isOpenSdk = (boolean) SpHelper.getData(X3Constent.IS_OPEN_SDK, false);
        X3StatusBarUtil.darkMode(this);
        swipeBackLayout.setEnableGesture(false);

        type = getIntent().getIntExtra("type",0);
        workBaseId = getIntent().getLongExtra("workBaseId",0L);
        carId = getIntent().getLongExtra("carId",0L);
        carNum = getIntent().getStringExtra("carNum");
        reportStatus = getIntent().getLongExtra("reportStatus", 0L);
        receiveBaseId = getIntent().getLongExtra("receiveBaseId",0L);

        initPage();
    }

    private void initPage() {
        ll_first.setVisibility(X3WorkType.Type_First == type ? View.VISIBLE : View.GONE);
        ll_alone.setVisibility(X3WorkType.Type_Alone == type ? View.VISIBLE : View.GONE);
        ll_work.setVisibility(X3WorkType.Type_Work == type ? View.VISIBLE : View.GONE);
        tv_content.setVisibility((X3WorkType.Type_Alone == type || X3WorkType.Type_Work == type) ? View.VISIBLE : View.GONE);
        tv_back.setVisibility((X3WorkType.Type_Alone == type || X3WorkType.Type_Work == type) ? View.VISIBLE : View.GONE);
        tv_start_ih.setVisibility((X3WorkType.Type_Alone == type || X3WorkType.Type_Work == type) ? View.VISIBLE : View.GONE);
        tv_send.setVisibility((X3WorkType.Type_Alone == type || X3WorkType.Type_Work == type) ? View.VISIBLE : View.GONE);

        switch ((int) type) {
            case X3WorkType.Type_Work:
                tv_status.setText(getString(R.string.x3_publish_report_success));
                tv_content.setText(getString(R.string.x3_publish_success_content));
                tv_start_ih.setText(getString(R.string.x3_start_work_order));
                break;
            case X3WorkType.Type_Alone:
                tv_refresh.setVisibility(reportStatus == 0 ? View.VISIBLE : View.GONE);
                tv_send.setVisibility(reportStatus == 0 ? View.GONE : View.VISIBLE);
                tv_start_ih.setVisibility(reportStatus == 0 ? View.GONE : View.VISIBLE);

                tv_start_ih.setText(getString(R.string.x3_start_alone_order));
                tv_status.setText(reportStatus == 0 ? getString(R.string.x3_publish_review) : getString(R.string.x3_publish_report_success));
                tv_content.setText(reportStatus == 0 ? getString(R.string.x3_submit_success_content) : getString(R.string.x3_publish_success_content));

                break;
            case X3WorkType.Type_First:
                tv_status.setText(getString(R.string.x3_finish_first_report));
                break;
        }
    }

    @OnClick({R2.id.tv_back,R2.id.tv_check,R2.id.tv_work,R2.id.tv_plan,R2.id.tv_send,
            R2.id.tv_refresh,R2.id.tv_start_ih,R2.id.tv_service_info,R2.id.tv_share})
    protected void onViewClick(View view){
        int id = view.getId();
        if (id == R.id.tv_back) {
            if (isOpenSdk) {
                finish();
            }else {
                EventBus.getDefault().post("UPDATE_CNACEL_ORDER");
                String simple = (String) SpHelper.getData(X3Constent.WORK_MODEL, "SIMPLE");
                Postcard build;
                if ("SIMPLE".equals(simple)) {
                    build = ARouter.getInstance().build(X3AppRouterConstants.Router.MAIN_MINI);
                } else {
                    build = ARouter.getInstance().build(X3AppRouterConstants.Router.MAIN_LUNCHER);
                }
                build.withFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK).navigation();
            }
        } else if (id == R.id.tv_check) {// 查看检测报告
            Bundle bundle = new Bundle();
            bundle.putBoolean("isDark",true);
            bundle.putString("title","查看检测报告页");
            bundle.putString("path", X3Constent.HOME_FINISH_DETAIL_MAIN_URL + "workBaseId=" + workBaseId + "&carNum=" + carNum);
            X3RouterCenter.startNavigate(X3AppRouterConstants.Router.GROUND_PUSH,bundle);

        } else if (id == R.id.tv_work) {
            Bundle bundle = new Bundle();
            bundle.putBoolean("isDark",true);
            bundle.putString("title","查看施工报告页");
            bundle.putString("path", X3Constent.HOME_FINISH_DETAIL_URL + "id=" + workBaseId);
            X3RouterCenter.startNavigate(X3AppRouterConstants.Router.GROUND_PUSH,bundle);

        } else if (id == R.id.tv_plan) {// 查看专属保养计划
            Bundle bundle = new Bundle();
            bundle.putBoolean("isDark",true);
            bundle.putString("title","查看专属保养计划页");
            bundle.putString("path", X3Constent.WORK_FINSH_CHECK_PLAN + "carId=" + carId);
            X3RouterCenter.startNavigate(X3AppRouterConstants.Router.GROUND_PUSH,bundle);

        } else if (id == R.id.tv_send) {// 发送检测报告
            Bundle bundle = new Bundle();
            bundle.putBoolean("isAlone",!(type == 0));
            bundle.putLong("workBaseId",workBaseId);
            X3RouterCenter.startNavigate(X3AppRouterConstants.Router.SEND_REPORT,bundle);
        }else if (id == R.id.tv_refresh) {
            if (mPresenter != null) {
                mPresenter.requestWorkBaseReportStatus(workBaseId);
            }
        }else if (id == R.id.tv_start_ih) {
            if (timer != null) {
                timer.cancel();
                timer.start();
            }
            isLoad = true;
            viewProxy.showLoading("");
            if (mPresenter != null) {
                mPresenter.openReportOnHub(workBaseId);
            }
        }else if (id == R.id.tv_share) {
            // 分享报告
            Bundle bundle = new Bundle();
            bundle.putBoolean("isDark",true);
            bundle.putString("title", "初检报告");
            bundle.putString("path", X3Constent.HOME_FIRST_ALONE_REPORT + receiveBaseId);
            X3RouterCenter.startNavigate(X3AppRouterConstants.Router.GROUND_PUSH,bundle);

        }else if (id == R.id.tv_service_info) {
            finish();
        }
    }

    @Override
    protected X3AloneFinishPresenter createPresenter() {
        return new X3AloneFinishPresenter();
    }

    private final CountDownTimer timer = new CountDownTimer(15 * 1000, 1000) {
        @Override
        public void onTick(long millisUntilFinished) {


        }

        @Override
        public void onFinish() {
            if (isFinishing()) {
                return;
            }
            isLoad = false;
            if (viewProxy != null) {
                viewProxy.hideLoading();
            }
            ToastUtils.show(getString(R.string.x3_open_ih_failed));
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("发布成功页");
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("发布成功页");
    }

    @Override
    public void getWorkBaseReportStatus(boolean isSuccess) {
        if (!isSuccess) {
            ToastUtils.show(getString(R.string.x3_no_review_success));
            return;
        }
        reportStatus = 1;
        initPage();
    }

    @Override
    public void openReportOnHubSuccess() {
        if (mPresenter != null) {
            mPresenter.getOpenReportStatus(workBaseId);
        }
    }

    @Override
    public void getOpenReportStatusSuccess(int status) {
        if (status == 2) {
            isLoad = false;
            if (timer != null) {
                timer.cancel();
            }
            viewProxy.hideLoading();
            ToastUtils.show(getString(R.string.x3_open_ih_success));
            Intent intent = new Intent(this,X3OpenIHSuccessActivity.class);
            intent.putExtra("workBaseId",workBaseId);
            startActivity(intent);
            finish();
            return;
        }
        if (status != 2 && isLoad) {
            if (delay == null) {
                delay = Observable.just(workBaseId)
                        .delay(3, TimeUnit.SECONDS);
            }
            delay.subscribe(new Observer<Long>() {
                @Override
                public void onSubscribe(@NonNull Disposable d) {

                }

                @Override
                public void onNext(@NonNull Long integer) {
                    if (mPresenter != null) {
                        mPresenter.getOpenReportStatus(workBaseId);
                    }
                }

                @Override
                public void onError(@NonNull Throwable e) {

                }

                @Override
                public void onComplete() {

                }
            });

            return;
        }

    }

    @Override
    public void recordingScreenOnHubSuccess() {

    }

    @Override
    public void getRecordingScreenStatusSuccess(int status) {

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
    }

    @Override
    public void onBackPressed() {
        EventBus.getDefault().post(new CloseWebviewAcivityBean());
        super.onBackPressed();
    }
}
